<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Builder;

class Post extends Model
{
    protected $table = 'posts';

    public function user()
    {
        return $this->belongsTo('App\Models\User', 'user_id', 'id');
    }

    public function comments()
    {
        return $this->hasMany('App\Models\Comment', 'post_id', 'id');
    }

    public function praises()
    {
        return $this->hasMany('App\Models\Praise', 'post_id', 'id');
    }

    //是否被某个用户点过赞
    public function praised($user_id = null)
    {
        if (!$user_id) {
            $user_id = \Auth::id();
        }
        $praise = $this->hasOne('App\Models\Praise', 'post_id', 'id')->where('user_id', $user_id)->first();
        return $praise;
    }

    public function postTopic()
    {
        return $this->hasMany('App\Models\TopicPost','post_id','id');
    }

    public function scopeAuthorBy(Builder $query)
    {
        return $query->where('user_id', \Auth::id());
    }

    public function scopeTopicNotIn(Builder $query, $topic_id)
    {
        return $query->doesntHave('postTopic','and',function ($q) use ($topic_id){
           $q->where('topic_id',$topic_id);
        });
    }

    public function getStatusAttribute($value){
        if($value == 0){
            return "正常";
        }
        if($value == 1){
            return "推荐";
        }
        if($value == -1){
            return "禁止";
        }
    }
    protected static function boot(){
        parent::boot();
        static::addGlobalScope('available',function(Builder $builder){
            $builder->whereIn('status',[0,1]);
        });
    }

}
